package com.ophiux.demo;


import com.aliyun.alink.dm.api.DeviceInfo;
import com.aliyun.alink.dm.api.InitResult;
import com.aliyun.alink.linkkit.api.ILinkKitConnectListener;
import com.aliyun.alink.linkkit.api.IoTMqttClientConfig;
import com.aliyun.alink.linkkit.api.LinkKit;
import com.aliyun.alink.linkkit.api.LinkKitInitParams;
import com.aliyun.alink.linksdk.channel.core.persistent.mqtt.MqttConfigure;
import com.aliyun.alink.linksdk.cmp.connect.channel.MqttPublishRequest;
import com.aliyun.alink.linksdk.cmp.connect.channel.MqttSubscribeRequest;
import com.aliyun.alink.linksdk.cmp.core.base.AMessage;
import com.aliyun.alink.linksdk.cmp.core.base.ARequest;
import com.aliyun.alink.linksdk.cmp.core.base.AResponse;
import com.aliyun.alink.linksdk.cmp.core.base.ConnectState;
import com.aliyun.alink.linksdk.cmp.core.listener.IConnectNotifyListener;
import com.aliyun.alink.linksdk.cmp.core.listener.IConnectSendListener;
import com.aliyun.alink.linksdk.cmp.core.listener.IConnectSubscribeListener;
import com.aliyun.alink.linksdk.tmp.device.payload.ValueWrapper;
import com.aliyun.alink.linksdk.tools.AError;
import com.aliyun.alink.linksdk.tools.ALog;
import org.eclipse.paho.client.mqttv3.MqttException;

import java.util.HashMap;
import java.util.Map;

public class Test {


    public static void main(String[] args) throws MqttException {

//        SubscribeSample.subscribe();
//        PublishSample.publish();

//        {
//            "ProductKey": "k0mahi4zn6H",
//            "DeviceName": "Device1",
//            "DeviceSecret": "cb51e77f0e0251042b374801eec0cb85"
//        }
        //k0mahi4zn6H.Device1|securemode=2,signmethod=hmacsha256,timestamp=1702887877675|


        String productKey = "k0mahi4zn6H";
        String deviceName = "Device1";
        String deviceSecret = "cb51e77f0e0251042b374801eec0cb85";
        final String iotInstanceId = "iot-06z00btaemny5hn";

        /**
         * step 1: 设置MQTT初始化参数
         */
//        IoTMqttClientConfig config = new IoTMqttClientConfig();

        /*
         *是否接受离线消息
         *对应MQTT的cleanSession字段
         */
//        config.receiveOfflineMsg = false;
//        LinkKitInitParams params = new LinkKitInitParams();
//
//        MqttConfigure.mqttHost = iotInstanceId + ".mqtt.iothub.aliyuncs.com:1883";
//        params.mqttClientConfig = config;

        /**
         * step 2: 设置初始化设备认证信息
         */
//        DeviceInfo deviceInfo = new DeviceInfo();
//        deviceInfo.productKey = productKey;
//        deviceInfo.deviceName = deviceName;
//        deviceInfo.deviceSecret = deviceSecret;
//        params.deviceInfo = deviceInfo;

        /**
         * step 3: 设置设备的username, token和clientId
         * 仅用于一型一密免预注册
         * 默认关闭
         */
        // MqttConfigure.deviceToken="${YourDeviceToken}";
        // MqttConfigure.clientId="${YourClientId}";


        //LinkKit底层是MQTT协议，设置MQTT初始化参数
        IoTMqttClientConfig config = new IoTMqttClientConfig();
        config.productKey = productKey;
        config.deviceName = deviceName;
        config.deviceSecret = deviceSecret;
        config.channelHost = iotInstanceId + ".mqtt.iothub.aliyuncs.com:1883";
        config.receiveOfflineMsg = false;//是否接受离线消息 对应MQTT的cleanSession字段

        // step 2: 设置初始化设备认证信息
        DeviceInfo deviceInfo = new DeviceInfo();
        deviceInfo.productKey = productKey;
        deviceInfo.deviceName = deviceName;
        deviceInfo.deviceSecret = deviceSecret;
        //报备的设备初始状态。
        Map<String, ValueWrapper> propertyValues = new HashMap<String, ValueWrapper>();

        LinkKitInitParams params = new LinkKitInitParams();
        params.mqttClientConfig = config;
        params.deviceInfo = deviceInfo;
        params.propertyValues = propertyValues;


        //连接并设置连接成功以后的回调函数。
        LinkKit.getInstance().init(params, new ILinkKitConnectListener() {
            public void onError(AError aError) {
                System.out.println("Init Error error= " + aError);
            }

            //初始化成功以后的回调。
            public void onInitDone(InitResult initResult) {
                System.out.println("Init done:" + initResult);

//                //设置Pub消息的Topic和内容。
//                MqttPublishRequest request = new MqttPublishRequest();
//                request.topic = "/" + productKey + "/" + deviceName + "/user/get";
//                request.qos = 0;
//                request.payloadObj = "{\"temperature\":35.0, \"time\":\"sometime\",\"msg\":\"连接成功\"}";
//                //发送消息并设置成功以后的回调。
//                LinkKit.getInstance().publish(request, new IConnectSendListener() {
//                    @Override
//                    public void onResponse(ARequest aRequest, AResponse aResponse) {
//                        System.out.println("onResponse:" + aResponse.getData());
//                    }
//
//                    @Override
//                    public void onFailure(ARequest aRequest, AError aError) {
//                        System.out.println("onFailure:" + aError.getCode() + aError.getMsg());
//                    }
//                });


                //设置订阅的Topic。
                MqttSubscribeRequest request = new MqttSubscribeRequest();
                request.topic = "/" + productKey + "/" + deviceName + "/user/get";
                request.isSubscribe = true;
                //发出订阅请求并设置订阅成功或者失败的回调函数。
                LinkKit.getInstance().subscribe(request, new IConnectSubscribeListener() {
                    @Override
                    public void onSuccess() {
                        System.out.println("======");
                    }

                    @Override
                    public void onFailure(AError aError) {

                    }
                });

                //设置订阅的下行消息到来时的回调函数。
                IConnectNotifyListener notifyListener = new IConnectNotifyListener() {
                    //此处定义收到下行消息以后的回调函数。
                    @Override
                    public void onNotify(String connectId, String topic, AMessage aMessage) {
                        System.out.println("received message from " + topic + ",内容:" + new String((byte[]) aMessage.getData()));
                    }

                    @Override
                    public boolean shouldHandle(String s, String s1) {
                        return false;
                    }

                    @Override
                    public void onConnectStateChange(String s, ConnectState connectState) {

                    }
                };
                LinkKit.getInstance().registerOnNotifyListener(notifyListener);
            }
        });

    }


}
